define(function(require, exports, module) {
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/js/component/rules.js");
	require("oa/act/js/loading.js");
	require("resource/js/component/vitoBooks/vitobooks.css");
	var actcont = require("oa/act/js/actcont.js");
	var painNodeForm = require("oa/act/main/js/paintNodeForm.js");
	var alertMsg = require("resource/js/component/alerts.js");
	var ajax = require("resource/js/component/ajax.js");

	var approverList=null;//实际审批人列表
	var approversMaxCount=0;//审批人数量
	var ccUserList = [];//存放抄送人
	var copyPersonList=[];//默认抄送人
	var noCopyPersonList=[];//新加抄送人
	
	exports.initPage=function(){
		using(["parser","layout","dialog","panel","datagrid", "textbox", "combobox", "datetimebox", "accordion", "numberbox","linkbutton"], function() {
			setTimeout(function() {
				addFormEvent();
				var nodeId=$("#processNodeId");
				if(nodeId.val() == actcont.startTask){//发起
					//初始化加载审批人
					approverInit($("#processKey").val());
					//条件审批绑定条件col事件，动态刷新审批人
					if($("#branchCol").length>0){
						var branchCol = $("#"+$("#branchCol").val());
						if(branchCol){
							var className = branchCol.attr("class");
							if (className.indexOf("easyui-combobox") >= 0) {
								branchCol.combobox({
									onSelect:function(des){
										approverInit($("#processKey").val(),des.id);
									}
								});
							} else if (className.indexOf("easyui-numberbox") >= 0) {
								if(window.attachEvent){//ie浏览器
									branchCol.next('span').find('.textbox-text')[0].attachEvent("onpropertychange",function (o){
										if(branchCol.numberbox('isValid')){
											approverInit($("#processKey").val(),o.srcElement.value||undefined);
										}
				                    });
								}else{
									branchCol.next('span').find('.textbox-text')[0].addEventListener("input",function(o){
										if(branchCol.numberbox('isValid')){
											approverInit($("#processKey").val(),o.target.value||undefined);
										}
					                },false);
								}
							}
						}
					};
					ajax.init().success(function(code,msg,data){//查询该流程默认抄送人
						if(code == 0){
							//加载抄送人
							copyPersonList=[];
							data.forEach(function(item){
								copyPersonList.push(item.userId);
							});
						   var html = "";
						   var colors = ['#229af9','#e91e63','#ffc107','#8bc34a','#3f51b5','#00bcd4'];
						   $.each(data,function(i,val){
								   var name = val.userName;
								   var text = name.substring(0,1);
								   var col_index = i%colors.length;
								   html = "<div class='approvers-item'>" +
										   "<div data-index="+val.userId+" class='approvers-item-person person-delete' style='background-color: "+colors[col_index]+"' title='点击移除 '>" +
											"<span class='name-first'>"+text+"</span>" +
											"</div>" +
											"<div class='personName'>"+name+"</div>" +
		   								  "</div>";
								   $("#addCopyOfUsers").parent().before(html);
								   ccUserList.push(val.userId);
						   });
						   $("#copyOfUsers").val("")
						   $("#copyOfUsers").val(JSON.stringify(ccUserList));	
						}
					}).contentType('application/json').sync().post(BASEPATH+"/oa/actCC/queryProcessCopyPerson.htm",JSON.stringify({processkey:$('#processKey').val()}));
				}
			},100);
		});
	}
	//预置审批人显示
	var paintApproverHtml = function(auditor,index){
		var nodeId = auditor.nodeId;
		var orderNum = auditor.orderNum;
		var nodeName=auditor.nodeName;
		var userType = auditor.userType;
		var users = auditor.users;
		var nameText = users[0].name;
		var firstNameText = nameText.substring(0,1);
		var colors = ['#229af9','#e91e63','#ffc107','#8bc34a','#3f51b5','#00bcd4'];
		var col_index=index%colors.length;
		var approver;
		var html = "<div class='approvers-item' id='"+nodeId+"'>" +
						"<div class='approvers-item-person' style='background-color: "+colors[col_index]+"'>" +
							"<span class='name-first'>"+firstNameText+"</span>" +
						"</div>" +
						"<div class='personName'>"+nameText+"</div>" +
						"<div class='approvers-item-type'>"+nodeName+"</div>" +
						"<div class='approvers-item-line'></div>" +
					"</div>";
		var result = {
			'userid' : function() {
				var id = "";
				if(users.length > 1){
					$("#approversDiv").append('<div style="width:auto;margin-left:7px;" class="approvers-item" id="'+nodeId+'"><div class="approvers-mutil"></div></div>');
					$.each(users,function(i,item){
						id += (item.id+',');
						var h =
							"<div class='mutil-item'>"+
						"<div class='approvers-item-person' style='background-color: "+colors[i%colors.length]+"'>" +
							"<span class='name-first'>"+item.name.substring(0,1)+"</span>" +
						"</div>" +
						"<div class='personName'>"+item.name+"</div></div>" ;
						$("#"+nodeId).find(".approvers-mutil").append(h);
					});
					var width = $("#"+nodeId).find(".approvers-mutil").width();
					$("#"+nodeId).append("<div class='approvers-item-line'></div>");
					$("#"+nodeId).append("<div class='approvers-item-type' style='width:"+(width+2)+"px;'>"+nodeName+"</div>");
					$("#"+nodeId).find(".approvers-mutil").width(width);
					$("#"+nodeId).width(width+27)
				}else{
					id = users[0].id;
					$("#approversDiv").append(html);
				}
				approver = {"nodeId":nodeId,"orderNum":orderNum,"userType":userType,"userId":id,approveStatus:1};
				approverList[orderNum-1] = approver;
			},
			'deptid' : function() {
				$("#approversDiv").append(html);
				approver = {"nodeId":nodeId,"orderNum":orderNum,"userType":userType,"userId":users[0].id,approveStatus:1};
				approverList[orderNum-1] = approver;
			},
			'director':function(){
				$("#approversDiv").append(html);
				approver = {"nodeId":nodeId,"orderNum":orderNum,"userType":userType,"userId":users[0].id,approveStatus:1};
				approverList[orderNum-1] = approver;
			},
			'roleid' : function() {
				var roleUsers = users;
				var color = col_index;
				var roleName = auditor.roleName;
				if(roleUsers.length == 0){
					approverList.splice(orderNum-1,1);
					return;
				}
				html = "<div class='approvers-item' id='"+nodeId+"'>" +
							"<div id='addApprover' class='approvers-item-person' style='background-color: #fff;border:1px solid #229af9' title='编辑'>"
								+ "<a class='addbtn' href='javascript:void(0)'>+</a>"+
							"</div>"+
							"<div class='personName'>添加</div>"+
							"<div class='approvers-item-type'>"+nodeName+"</div>" +
							"<div class='approvers-item-line'></div>" +
						"</div>";
				$("#approversDiv").append(html);
				if($("#"+nodeId)){
					$("#"+nodeId).find("#addApprover").unbind("click");
					$("#"+nodeId).find("#addApprover").bind('click',function(){
						openDialog(roleName);
						require.async("resource/js/component/treeutil.js", function(treeUtil){
							var tree = new treeUtil.ajaxTree({
								eid: "common_select",
								localData: roleUsers,
								check: "radio",
								title:roleName,
								data: {
									simpleData: {
										enable: true,
										idKey: "id",
										pIdKey: "pid",
										rootPId: 0
									}
								},
								save: function(data) {
									if(!data || data.length ==0 || !data[0].id){
										alertMsg.show("请选择审批人");
										return;
									}
									$("#"+nodeId).find("#addApprover").css("background-color",colors[color]);
									$("#"+nodeId).find("#addApprover").siblings(".personName").text(data[0].name);
									$("#"+nodeId).find("#addApprover").find("a").text(data[0].name.substring(0,1));
									$("#"+nodeId).find("#addApprover").find("a").removeClass("addbtn");
									$("#"+nodeId).find("#addApprover").find("a").addClass("name-first");
									approver = {"nodeId":nodeId,"orderNum":orderNum,"userType":userType,"userId":data[0].id.toString(),"approveStatus":1};
									approverList[orderNum-1] = approver;
								}
							});
							tree.load();
						});
					})
				}
			}
		};
		result[auditor.userType]();
	}
	var printDefinedApprover = function(data){
		require.async("resource/js/component/vitoBooks/vitobooks.js",function(){
			var addBtn = "<div class='approvers-item'>" +
			"<div id='addApprover' class='approvers-item-person' style='background-color: #fff;border:1px solid #229af9' title='添加'>"
				+ "<a class='addbtn' href='javascript:void(0)'>+</a>"+
			"</div>"+
			"<div class='personName'>添加</div>"+
			"<div class='approvers-item-line'></div>" +
			"</div>";
			$("#approversDiv").append(addBtn);
			$("#approversDiv").data('approvers',data);
			$("#addApprover").bind('click',data,function(){
				if(printDefinedApprover.dlg){
					printDefinedApprover.dlg.vitoBooks("open");
				}else{
					printDefinedApprover.dlg = $("<div id='approverDlg'></div>").appendTo("body").vitoBooks({
						title: '审批人',
						checkType:"checkbox",
						defaultUrl:'user',
						nodeType : 'user',
						closed: false,
						beforeSave : function(nodes){
						   if((approverList.length+nodes.length)>approversMaxCount){
							   this.alert('最多设置'+approversMaxCount+'位审批人');
							   return false;
						   }
						   return true;
						},
						onSave:function(nodes){
						   var html = "";
						   var colors = ['#229af9','#e91e63','#ffc107','#8bc34a','#3f51b5','#00bcd4'];
						   $.each(nodes,function(i,node){
							   var firstNameText = node.name.substring(0,1);
							   var col_index = i%colors.length;
							   var node_index = approverList.length;
							   html += "<div class='approvers-item'>" +
											"<div data-index="+node_index+" class='approvers-item-person person-delete' style='background-color: "+colors[col_index]+"' title='点击移除 '>" +
											"<span class='name-first'>"+firstNameText+"</span>" +
											"</div>" +
											"<div class='personName'>"+node.name+"</div>" +
											"<div class='approvers-item-type' title='"+data[node_index].nodeName+"'>"+data[node_index].nodeName+"</div>" +
											"<div class='approvers-item-line'></div>" +
										"</div>";
							   approverList.push({
								   nodeId:data[node_index].nodeId,
								   orderNum:data[node_index].orderNum,
								   userType:"userId",
								   userId:node.id.toString(),
								   approveStatus:1});
						   });
						   $("#addApprover").parent().before(html);
						}
					});
				}
			});
		})
	};

	$("#approversDiv").on('click','.person-delete',function(){
		//var index = $(this).data("index");
		var index = $("#approversDiv .person-delete").index(this);
		var data = $("#approversDiv").data("approvers");
		approverList.splice(index,1);
		$.each(approverList,function(i,val){
			val.nodeId = data[i].nodeId;
			val.orderNum = data[i].orderNum;
		});
		$(this).parent().remove();
		$.each($('.approvers-item-type'),function(i,val){
			$(this).text(data[i].nodeName);
		})
	})
	//加载审批人
	var approverInit = function(key,branchVal){
		ajax.init().success(function(code,msg,data){
			if(code==0){
				$("#approversDiv").empty();
				if(data.hasSet){
					if(data.approvers && data.approvers.length > 0){
						var html="";
						approversMaxCount = data.approvers.length;
						approverList = new Array(approversMaxCount);
						$.each(data.approvers,function(i,val){
							paintApproverHtml(val,i);
					   });
						var promp = "<span>审批人已由管理员预置</span>"
						if(data.distinct){
							promp += "<span>（已为您自动去重）</span>"
						}
						$("#promptDiv").html(promp)
					}else{
						ajax.init().success(function(code,msg,data1){
							if(code == 0){
								approversMaxCount = data1.length;
								approverList = [];
								$("#promptDiv").html("<span>审批人已由管理员预置（未找到指定条件审批人）</span>")
								printDefinedApprover(data1);
							}
						}).post(BASEPATH+"/oa/act/approver/queryProcessAllNode.htm" ,{processKey:$("#processKey").val()})
					}
				}else{
					ajax.init().success(function(code,msg,data){
						if(code == 0){
							approversMaxCount = data.length;
							approverList = [];
							$("#promptDiv").html("<span>自定义添加（该流程添加审批人最大数量："+approversMaxCount+"人）</span>")
							printDefinedApprover(data);
						}
					}).post(BASEPATH+"/oa/act/approver/queryProcessAllNode.htm" ,{processKey:$("#processKey").val()})
				}
			}
			$('#btnsWarp').find('.easyui-linkbutton ').linkbutton("enable");
		}).post(BASEPATH+"/oa/act/approver/queryProcessApproversInfo.htm",{"processKey":key,"des":branchVal})
	}

	function addFormEvent(){
		if($('#processNodeId').val() != actcont.startTask){
			var key = $('#processKey').val();
			var bussId = $("#busenessId").val();
			var taskId = $("#taskId_0").val();
			var nodeId = $("#processNodeId_0").val();
			loadView(key,bussId,taskId,nodeId);
		}
		addInputEvent($("#processForm").find(".tdValue>.textbox-text"));
		addInputEvent($(".subsForm").find(".input-value>.textbox-text"));
		loadSubs();
		loadBtns();
		abstractDialog();
		//添加抄送人
		$("#addCopyOfUsers").click(function() {
			addCopyOfUsersFuc();
		});
	};

	var addCopyOfUsersFuc = function (){
		require.async("resource/js/component/vitoBooks/vitobooks.js",function(){
//			if(addCopyOfUsersFuc.dlg && addCopyOfUsersFuc.dlg.dialog){
//				addCopyOfUsersFuc.dlg.vitoBooks("open");
//			}else{
				addCopyOfUsersFuc.dlg = new $("<div id='ccdlg'></div>").appendTo("body").vitoBooks({
					checkType:"checkbox",
					defaultUrl:'user',
					nodeType : 'user',
					closed: false,
					title:"抄送人员选择",
					backfill:true,
					checks:copyPersonList,
					onSave:function(nodes){
					   var html = "";
					   var colors = ['#229af9','#e91e63','#ffc107','#8bc34a','#3f51b5','#00bcd4'];
					   $.each(nodes,function(i,val){
						   if($.inArray(val.id,ccUserList)==-1){
							   var name = val.name;
							   var text = name.substring(0,1);
							   var col_index = i%colors.length;
							   var node_index = val.id;
							   html = "<div class='approvers-item'>" +
									   "<div data-index="+node_index+" class='approvers-item-person person-delete' style='background-color: "+colors[col_index]+"' title='点击移除 '>" +
										"<span class='name-first'>"+text+"</span>" +
										"</div>" +
										"<div class='personName'>"+name+"</div>" +
	   								  "</div>";
							   $("#addCopyOfUsers").parent().before(html);
							   ccUserList.push(val.id);
							   noCopyPersonList.push(val.id);
						   }
					   });
//					   $("#copyOfUsers").val("")
					   $("#copyOfUsers").val(JSON.stringify(ccUserList));
					}
				});
				
//			}
		});
	};

	$("#copyOfUsersDiv").on('click','.person-delete',function(){
		var userId = $(this).data("index").toString();
		var index=ccUserList.indexOf(userId);
		if(noCopyPersonList.indexOf(userId) >= 0){//只能移除不是默认抄送人
			$(this).parent().remove();
			ccUserList.splice(index,1);
		}
		$("#copyOfUsers").val("")
	    $("#copyOfUsers").val(JSON.stringify(ccUserList));
	});

	function addInputEvent(ins) {
		$.each(ins, function(i, input) {
			var opt;
			if ($.data(input).validatebox) {
				opt = $.data(input).validatebox.options;
			} else if($.data(input).textbox){
				opt = $.data(input).textbox.options;
			}else{
				opt = eval('('+$(input).data().options+')');
			}
			var showType = opt.showType;
			if (showType == actcont.showType.FORM_SHOWTYPE_MSELECT && opt.dataId && opt.dataId != '') {
				var dataId = opt.dataId;
				if (dataId.indexOf("UC") == 0) { //用户自定义流程下拉框
					comboxmLoad(opt.id, dataId);
				}
			} else if (showType == actcont.showType.FORM_SHOWTYPE_SELECT && opt.dataId && opt.dataId != '') {
				var dataId = opt.dataId;
				if (dataId.indexOf("UC") == 0) { //用户自定义流程下拉框
					comboxUserLoad(opt.id, dataId);
				} else if(dataId == "link"){
					if(opt.dataSource){
						comboxLoad(opt.id, null,null,opt.dataSource);
					}
				}else if(dataId == "basecode") {
					//加载下拉框数据
					var dataSource = opt.dataSource;
					if(dataSource && dataSource != ''){
						var source = dataSource.split(',');
						comboxLoad(opt.id, dataId, getComboxParam(source));
					}else{
						comboxLoad(opt.id, dataId, '');
					}
				}
				//绑定联动字段
				var dataOnchange = opt.dataOnchange;
				if(dataOnchange && $('#'+dataOnchange).length > 0){
					var $obj = $('#'+opt.id);
					var $target = $('#'+dataOnchange);
					var options = eval('({'+$target.data('options')+'})');
					if(options.showType == actcont.showType.FORM_SHOWTYPE_SELECT){
						$obj.combobox({
							onChange:function(newVal,oldVal){
								comboxLoad(dataOnchange, options.dataId, newVal);
							}
						});
					}else if(options.showType == actcont.showType.FORM_SHOWTYPE_HIDDEN){
						$obj.combobox({
							onChange:function(newVal,oldVal){
								$target.val(newVal);
							}
						});
					}
				}
			}else if ((showType == actcont.showType.FORM_SHOWTYPE_MTREE || showType == actcont.showType.FORM_SHOWTYPE_TREE) && opt.dataId && opt.dataId != '') {
				//单击加载树
				$(input).bind("click", function() {
					require.async("resource/js/component/treeutil.js", function(treeutil) {
						openDialog(opt.colNameCh);
						var tree = new treeutil.ajaxTree(getTreeSetting(showType, opt.dataId, opt.id, opt.dataSource, opt.colNameCh));
						tree.load();
					});
				});
			} else if (showType == actcont.showType.FORM_SHOWTYPE_FILE) {
				//上传文件
				using("upload", function() {
					$(input).next('.textbox').unbind("click");
					$(input).next('.textbox').bind("click", function() {
						$("#" + opt.id).upload({
							param: {
								exts: '.bmp,.gif,.jpg,.pic,.png,.tif,.txt,.pdf,.doc,.docx,.html,.xls,.xlsx,.ppt,.pptx,.dot,.wps,.wav,.aif,.au,.mp3,.ram,.wma,.mmf,.amr,.aac,.flac,.rar,.zip,.arj,.gz,.z'
							}
						});
						$("#" + opt.id).upload("show");
					});
				});
			}else if(showType== actcont.showType.FORM_SHOWTYPE_BOOKS){//通讯录
				require.async("resource/js/component/vitoBooks/vitobooks.js",function(){
					var books = $(input).next('.textbox').vitoBooks({
						checkType:opt.dataId,
						defaultUrl:opt.dataSource,
						nodeType : opt.dataSource,
						closed: true,
						checks:$('#'+opt.id).val().split(','),
						onSave:function(nodes){
							var text = '';
							var value = '';
							$.each(nodes,function(i,item){
								text += item.name+',';
								value += item.id +',';
							});

							$('#books-'+opt.id).textbox('setValue',text.substring(0,text.length-1));
							$('#'+opt.id).val(value);
						}
					});
					$(input).next('.textbox').unbind('click');
					$(input).next('.textbox').bind('click',function(){
						books.vitoBooks('open');
					})
				});
			}else if(showType== actcont.showType.FORM_SHOWTYPE_SIGN){
				require.async("resource/js/component/drawBoard/drawBoard.js",function(app){
					$(input).drawBoard({
						width:500,
						height:350,
						onSave:function(imgUrl){
							$('#'+opt.id+'-img').height($('#'+opt.id+'-btn').innerHeight());
							$('#'+opt.id+'-img').attr('src',imgUrl);
							$('#'+opt.id).val(imgUrl);
						}
					});
					$(input).find('#'+opt.id+'-btn').click(function(){
						$(input).drawBoard("open");
					});
				 });

			}
		});
	}

	var gotoDetailDialog = function(dialog,title) {
		dialog.dialog({
			width:420,
			height:600,
		    title: title,
		    href :BASEPATH+'/oa/act/main/abstractStatistics.HTML',
		    cache: true,
		    onLoad:function(){
			   	 seajs.use("/oa/act/main/js/abstractStatistics.js",function(app){
			   		 app.init();
			   	 });
		    },
		    modal: true
		});
	}

	function abstractDialog(){
		$("#historicalData").bind("click", function(){
			var historicalData = $(this).data("dialog")||$("<div id='oa-historicalData' style='overflow-y:auto;'></div>");
			if(historicalData.data("dialog")){
				gotoDetailDialog(historicalData,$(this).data('title'));
			}else{
				gotoDetailDialog(historicalData,$(this).data('title'));
				$(this).data("dialog",historicalData);
			}
		});
	}

	function comboxLoad(id, dataId, param,url) {
		require.async("resource/js/component/combox.js", function(combox) {
			combox.loadCombox({
				id: "#" + id,
				queryId: dataId,
				param: param,
				urlPath:url
			});
		});
	}

	function comboxUserLoad(id, dataId) {
		require.async("resource/js/component/combox.js", function(combox) {
			combox.loadCombox({
				id: "#" + id,
				queryId: "actcode",
				param: dataId
			});
			//combox.loadCombox({id:"#"+id,urlPath:"/pro/comm/proCommunity/queryProUserComm.htm"});
		});
	}

	function comboxmLoad(id, dataId) {
		require.async("resource/js/component/combox.js", function(combox) {
			combox.loadCombox({
				id: "#" + id,
				queryId: "actcode",
				param: dataId,
				exConf:{
					multiple:true
				}
			});
			//combox.loadCombox({id:"#"+id,urlPath:"/pro/comm/proCommunity/queryProUserComm.htm"});
		});
	}

	function getComboxParam(dataOnchanges) {
		var param = "";
		$.each(dataOnchanges, function(i, dataOnchange) {
			if ($("#" + dataOnchange).length > 0) {
				param += $("input[name='" + dataOnchange + "']").val();
			} else {
				param += dataOnchange;
			}
			if (i > 0) {
				param += ",";
			}
		});
		return param;
	}

	function getTreeSetting(checkbox, queryId, id, dataOnchange, title) {
		if (checkbox == actcont.showType.FORM_SHOWTYPE_MTREE) {
			checkbox = 'checkbox';
		} else if (checkbox == actcont.showType.FORM_SHOWTYPE_TREE) {
			checkbox = 'radio';
		}
		var param = "";
		if (dataOnchange && dataOnchange != '') {
			param = getComboxParam(dataOnchange.split(","));
		}
		var settings = {
			title: title,
			data: {
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pid",
					isParentKey: "isparent",
					rootPId: null
				}
			},
			check: checkbox,
			eid: "common_select",
			url: BASEPATH + "/base/authoriza/conmonData/queryDataNoCache.htm?queryId=" + queryId + "&param=" + param,
			save: function(data) {
				if (checkbox == 'radio') {
					$("#" + id + "_name").textbox("setValue", data[0].name);
					$("#" + id).val(data[0].id);
				} else if (checkbox == 'checkbox') {
					var name = "";
					var ids = "";
					$.each(data, function(i, obj) {
						name += obj.name;
						ids += obj.id;
						if (i > 0) {
							name += ",";
							ids += ",";
						}
					});
					$("#" + id + "_name").textbox("setValue", name);
					$("#" + id).val(ids);
				}
			}
		}
		return settings;
	}

	function openDialog(title) {
		$("#common_select").dialog({
			title: title,
			closed: true,
			modal: true,
			buttons: [{}]
		});
		$("#common_select").dialog("open").dialog('resize',{top:(window.innerHeight-$("#common_select").dialog("options").height)/2});
	}

	function loadView(key,bussId) {
		painNodeForm.loadView(key,bussId);
	};
	function loadSubs() {
		if (typeof subs == 'undefined') {
			return;
		}
		if (subs && subs.length > 0) {
			var loadjs = [];
			$.each(subs, function(i, sub) {
				var id = sub.tab.id;
				var dg = null;
				cols = sub.cols;
				$.each(cols, function(i, col) {
					var type = col.editor.type;
					if (col.isRequire_ == '0') {
						col.editor.options.required = true;
					}
					if(col.colLength_){
						col.editor.options.validType=["maxlength["+col.colLength_/2+"]"];
					}
					if (type == actcont.showType.FORM_SHOWTYPE_HIDDEN) {
						col.hidden = true;
					} else if (type == actcont.showType.FORM_SHOWTYPE_SELECT) {
						col.editor.options.valueField = "id";
						col.editor.options.textField = "text";
						col.editor.options.url = BASEPATH + "/base/authoriza/conmonData/queryData.htm?queryId=" + col.dataId_ + "&param=" + col.dataSource_;
						col.editor.options.loadFilter = function(data) {
							return data.data;
						}
					} else if (type == actcont.showType.FORM_SHOWTYPE_INTEGER) {
						col.editor.options.precision = "0";
						col.editor.options.validType='max[9999999999]';
					} else if (type == actcont.showType.FORM_SHOWTYPE_NUMBER) {
						col.editor.options.precision = "2";
						col.editor.options.validType='max[99999999.99]';
					} else if (type == actcont.showType.FORM_SHOWTYPE_FILE) {

					} else if ((type == actcont.showType.FORM_SHOWTYPE_TREE || type == actcont.showType.FORM_SHOWTYPE_MTREE) && col.dataId_ && col.dataId_ != '') {
						//下拉框树
						col.editor.options.url = BASEPATH + "/base/authoriza/conmonData/queryData.htm?queryId=" + col.dataId_ + "&param=" + col.dataSource_;
						col.editor.options.ztreeopt = {};
						col.editor.options.ztreeopt.data = {
							simpleData: {
								enable: true,
								idKey: "id",
								nameKey: "name",
								pIdKey: "pid"
							}
						};
						col.editor.options.ztreeopt.check = {};
						if (type == actcont.showType.FORM_SHOWTYPE_TREE) {
							col.editor.options.ztreeopt.check.chkStyle = 'radio';
						} else {
							col.editor.options.ztreeopt.check.chkStyle = 'checkbox';
						}
					}
					col.editor.type = actcont.easyRelation[type];
					loadjs.push(actcont.easyRelation[type]);
				});
				loadjs = $.unique(loadjs);

				var config = {
					columns: [sub.cols],
					fitColumns: true,
					singleSelect: false,
					striped: true,
					autoRowHeight: true,
					resizeHandle: true,
					nowrap: true,
					checkbox: true,
					rownumbers: true,
					frozenColumns: [
						[{
							field: 'ck',
							checkbox: true
						}]
					],
					toolbar: {
						title: {
							_class: "",
							text: sub.tab.name
						},
						btn: [{
							iconCls: 'icon-add',
							text: "添加",
							handler: function() {
								dg.datagrid("appendRow", {
									_editing: true
								});
//									dg.parent().height(dg.parent().height() + 45);
//									dg.parent().parent().height(dg.parent().parent().height() + 46);
								dg.datagrid("beginEdit", dg.datagrid("getRows").length - 1);
							}
						}, {
							iconCls: 'icon-remove',
							url: '/party/news/deletePartyNews.htm',
							text: "删除",
							needRow:true,
							handler: function(a, b) {
								var selectRows = dg.datagrid("getSelections");
								var allRows = dg.datagrid("getRows");
								if(selectRows.length == 0){
									alertMsg.alert('请选择要删除的行');
								}else if (allRows.length == selectRows.length) {
									alertMsg.alert('表格应该至少保留一行数据');
								} else {
									alertMsg.confirm('确认删除吗？', function(r) {
										if (r) {
											$.each(selectRows, function(i, row) {
												dg.datagrid("deleteRow", dg.datagrid("getRowIndex", row));
//													dg.parent().height(dg.parent().height() - 45);
//													dg.parent().parent().height(dg.parent().parent().height() - 45);
											});
										}
									});
								}
							}
						}]
					}
				};
				if (loadjs.length > 0) {
					using(loadjs.concat(["parser"]), function() {
						dg = $("#" + id).datagrid(config);
						var p = dg.closest(".panel-body");
//							p.height(p.height() + 45);
						dg.datagrid("appendRow", {
							_editing: true
						});
//							dg.parent().height(dg.parent().height() + 45);
//							dg.parent().parent().height(dg.parent().parent().height() + 46);
						dg.datagrid("beginEdit", dg.datagrid("getRows").length - 1);
						var ed = dg.datagrid("getEditors", dg.datagrid("getRows").length - 1)[0];
					})
				} else {
					dg = $("#" + id).datagrid(config);
					dg.datagrid("appendRow", {
						_editing: true
					});
//						dg.parent().height(dg.parent().height() + 45);
//						dg.parent().parent().height(dg.parent().parent().height() + 46);
					dg.datagrid("beginEdit", dg.datagrid("getRows").length - 1);
				}

			});
		}
	}

	function setUrlParam() {
		var btns = $("#btnsWarp").find("a")
		$.each(btns, function(i, input) {
			if ($(input).data('options') != undefined) {
				var processDatas = JSON.stringify($(input).data('options'));
				var processData = {};
				if (processDatas != "" && processDatas.length > 0) {
					processData = eval('(' + processDatas + ')');
					//流程设置js校验
					if (processData != null) {
						if (processData.hasOwnProperty("loadJs")) {
							var loadJs = processData.loadJs;
							if (loadJs != null && loadJs != "") {
								loadJs = loadJs.replace(/\^/g, "\"");
								eval("var temp =" + loadJs);
								require.async('resource/js/component/ajax.js', function(ajax) {
									temp(ajax, BASEPATH, alertMsg, '0');
								});
							}
						}
						if (processData.hasOwnProperty("loadJsName")) {
							if (processData.loadJsName == "setOverTime") {
								//setOverTime();
							}
						}
					}
				}
			}
		});
	}

	//TODO 需要修复时间控件
//	function setOverTime() {
//		$("#overtime-overtime_time").numberbox({
//			disabled: true
//		});
//		var flag = false;
//		if($("#branchCol").length>0){
//			var branchCol = $("#"+$("#branchCol").val());
//			if($("#branchCol").val()=='overtime-overtime_time'){
//				flag = true;
//			}
//		}
//		$("#overtime-start_time").datetimebox({
//			onChange: function(value, oldval) {
//				debugger
//				oldval = oldval.substring(0,oldval.lastIndexOf(":"))
//				if (value == oldval) {
//					return;
//				}
//				//以下写onchange的逻辑
//				var endTime = $("#overtime-end_time").datetimebox('getValue');
//				if (value != null && value != "" && endTime != null && endTime != "") {
//					var sDate = new Date(value);
//					var eDate = new Date(endTime);
//					if (sDate >= eDate) {
//						alertMsg.alert("开始时间不能大于结束时间！");
//						return;
//					} else {
//						var dateHour = eDate.getTime() - sDate.getTime();
//						var num = dateHour / (3600 * 1000); //计算开始时间结束时间相差几个小时，精确到小数点后1位
//						$("#overtime-overtime_time").textbox('setValue', num.toFixed(1));
//						if(flag){
//							approverInit($("#processKey").val(),$("#overtime-overtime_time").numberbox('getValue')||undefined);	}
//						}
//				}
//			}
//		});
//		$("#overtime-end_time").datetimebox({
//			onChange: function(value, oldval) {
//				oldval = oldval.substring(0,oldval.indexOf(":"))
//				if (value == oldval) {
//					return;
//				}
//				//以下写onchange的逻辑
//				var startTime = $("#overtime-start_time").datetimebox('getValue');
//				if (value != null && value != "" && startTime != null && startTime != "") {
//					var sDate = new Date(startTime);
//					var eDate = new Date(value);
//					if (sDate >= eDate) {
//						alertMsg.alert("开始时间不能大于结束时间！");
//						return;
//					} else {
//						var dateHour = eDate.getTime() - sDate.getTime();
//						var num = dateHour / (3600 * 1000); //计算开始时间结束时间相差几个小时，精确到小数点后1位
//						$("#overtime-overtime_time").textbox('setValue', num.toFixed(1));
//						if(flag){
//							approverInit($("#processKey").val(),$("#overtime-overtime_time").numberbox('getValue')||undefined);
//						}
//					}
//				}
//			}
//		});
//	}

	//转发
	var transferInit = function(){
		require.async("resource/js/component/vitoBooks/vitobooks.js",function(){
			if(transferInit.dlg){
				transferInit.dlg.vitoBooks("open");
			}else{
				transferInit.dlg = $("<div></div>").appendTo("body").vitoBooks({
					title:"企业通讯录",
/*					width:400,
					height:410,	*/
					nodeType : 'user',
					defaultUrl : 'user',
					checkType : 'checkbox',
					beforeCheck : function(node){
						var currentUserId = $('#currentUserId').val();
						if(currentUserId == node.id){
							this.alert('不能转交给自己');
							return false;
						}
						return true;
					},
					onSave : function(node){
					   var checkUserId = node[0].id.toString().trim();
					   var taskId = $("#taskId").val();
					   showLoading()
					   ajax.init().success(function(msg,code,data){
						   	hideLoading()
							window.parent.$('.close').click();
							window.parent.location.reload();
						}).error(function(){
						 	hideLoading();
						}).post(BASEPATH+"/oa/act/activitiMain/transfer.htm",{taskId:taskId,userId:checkUserId});
					}
				});
			}
		});
	}
	//按钮是否被禁用
	function btnDisabled(jq){
		return jq.linkbutton('options').disabled;
	}
	//遮罩
	function showLoading() {
		$('body').loading({msg:'提交中'});
	}

	function hideLoading() {
		$('body').loading('hide');
	}
	//盖章
	function seal(){
		ajax.init().sync().success(function(code,msg,data){
			if(code == 0 && data.length > 0){
				var seal = data[0].path;
				$('<input id="seal" type="hidden">').val(seal).appendTo('body')
			}
		}).post(BASEPATH+'/oa/seal/querySealByUser.htm');
	}
	//签名
	var openSignDlg = function(onSave){
		openSignDlg.dlg = $('<div></div>').appendTo('body').dialog({
				title:'密码签名',
				href:BASEPATH+'/view/oa/act/main/signDlg',
				modal:true,
				closed:false,
				width:400,
				height:250,
				onLoad:function(){
					$('#jumpSet').bind('click',function(){
						indexApp.exec("openMenu", '180803133151000191');
					});
				},
				buttons:[{
					text:'确定',
					handler:function(){
						if($.isFunction(onSave)){
							require.async('resource/js/component/md5.js', function(MD5){
								var pwsVal = $('#signPassword').val();
								if(!pwsVal){
										alertMsg.show('请输入密码');
									return;
								}
								var md5Input = MD5.md5(pwsVal).toUpperCase();
								ajax.init().sync().success(function(code,msg,data){
									if(code == 0){
										$('#signPath').val(data.rows[0].sealName);
										onSave.call();
									}else{
										alertMsg.show('请先设置签名');
									}
								}).post(BASEPATH+'/archive/user/getUserSignatureByverifyType.htm',{
										verifyType:"pwd",
										password:md5Input
								});
							});
						}
					}
				},{
					text:'取消',
					handler:function(){
						openSignDlg.dlg.dialog('close');
					}
				}],
				onClose:function(){
					openSignDlg.dlg.dialog('destroy');
					openSignDlg.dlg = null;
				}
			});
	}
	function loadBtns() {
		setUrlParam();
		var processInstanceId = $("#processInstanceId").val();
		var bussId = $("#busenessId").val();
		//当前登录用户ID
		var currentUser = $("#currentUserId").val();
		var taskId = $("#taskId").val();
		var key = $("#processKey").val();
		var processNodeId = $("#processNodeId").val();
		//绑定终止按钮事件
		if (typeof($("#endProcess")) != 'undefined' && $("#endProcess").length > 0) {
			$("#endProcess").unbind("click");
			$("#endProcess").bind("click", function() {
				var btn = this;
				require.async('oa/act/main/js/submit.js', function(submit){
					if(btnDisabled($(btn))){
						return
					}
					var form  = submit.checkForm(btn);
					if(form){
						showLoading();
						ajax.init().success(function(code, msg, datas) {
							hideLoading();
							window.parent.$('.close').click();
							window.parent.location.reload();
						}).error(function(code, msg, datas) {
							hideLoading();
							$.messager.show("系统通知",btnName+"异常");
						}).contentType('application/json')
						.post(BASEPATH + '/oa/act/activitiMain/endProcess.htm', JSON.stringify(form));
					}
				});
			});
		}
		//指派
		if (typeof($(".assignProcess")) != 'undefined' && $(".assignProcess").length > 0) {
			require.async(["resource/js/component/vitoBooks/vitobooks.js",'oa/act/main/js/submit.js'],function(a,submit){
				ajax.init().success(function(code, msg, data) {
					var maxCount =data.maxAssign;
					var type = maxCount == 1?"radio":"checkbox";
					$(".assignProcess").unbind("click");
					$(".assignProcess").bind("click", function() {
						var btn = this;
						var isSeal = $('#isSeal').val();
						isSeal && isSeal == '1' && seal();
						var form  = submit.checkForm(btn);
						if(form){
							if(btn.dlg){
								btn.dlg.vitoBooks("open");
							}else{
								btn.dlg = $("<div></div>").appendTo("body").vitoBooks({
									title:"企业通讯录",
									width:400,
									height:400,
									defaultUrl:'user',
									nodeType : 'user',
									checkType : type,
									beforeCheck : function(node){
										var currentUserId = $('#currentUserId').val();
										if(currentUserId == node.id){
											this.alert('不能指派给自己');
											return false;
										}
										return true;
									},
									beforeSave : function(nodes){
										if(maxCount != -1 && maxCount<nodes.length){
										   this.alert('最多指派'+maxCount+'位审批人');
										   return false;
										}
									   return true;
									},
									onSave : function(nodes){
										if(btnDisabled($(btn))){
											return
										}
									   var checks=[];
									   $.each(nodes,function(index,node){
										   checks.push(node.id);
									   });
									   form.info.assignUserId = checks.toString();
									   submit.submitForm(btn,form);
									}
								});
							}
						}
					});
				}).post(BASEPATH + '/oa/act/approver/queryNextNode.htm', {
					processKey: key,
					currentNodeId: $("#processNodeId").val()
				});
			});
		}

		//流程同意/驳回
		if (typeof($(".assignRoleProcess")) != 'undefined' && $(".assignRoleProcess").length > 0) {
			require.async('oa/act/main/js/submit.js', function(submit) {
				$(".assignRoleProcess").unbind("click");
				$(".assignRoleProcess").bind("click", function(){
					var btn = this;
					if(btnDisabled($(this))){
						return
					}
					var isSeal = $('#isSeal').val();
					isSeal && isSeal == '1' && seal();
					var result = submit.checkApprover(approverList);
					var code = result.code;
					if(code == 0){
						var form = submit.checkForm(btn,result.data)
						if(form){
							var isSign = $('#isSign').val();
							if(isSign === '1'){
								openSignDlg(function(){
									submit.submitForm(btn,form);
								});
							}else{
								submit.submitForm(btn,form);
							}
						}
					}else if(code == 1){
						alertMsg.alert(result.msg);
						return;
					}else if(code == 2){
						$.messager.confirm("系统提示","您的审核人设置不完整，确定要提交吗？",function(r){
							if(r){
								var form = submit.checkForm(btn,result.data)
								if(form){
									var isSign = $('#isSign').val();
									if(isSign === '1'){
										openSignDlg(function(){
											submit.submitForm(btn,form);
										});
									}else{
										submit.submitForm(btn,form);
									}
								}
							}
						});
					}
				})
			});
		}
		//转发事件
		if(typeof($('#transfer')) != 'undefined' &&$('#transfer').length > 0 ){
			$("#transfer").unbind("click");
			$("#transfer").bind("click",function(){
				if(btnDisabled($(this))){
					return
				}
				transferInit();
			});
		}
		//挂起事件
		if (typeof($("#hangUp")) != 'undefined' && $("#hangUp").length > 0) {
			$("#hangUp").unbind("click");
			$("#hangUp").bind("click", function() {
				if(btnDisabled($(this))){
					return
				}
				showLoading();
				require.async('resource/js/component/ajax.js', function(ajax) {
					ajax.init().success(function(code, msg, datas) {
						hideLoading();
						window.location.reload();
					}).error(function(code, msg, datas) {
						hideLoading();
						alertMsg.alert("挂起失败！");
					}).post(BASEPATH + '/oa/act/activitiMain/hangUp.htm', {
						processInstanceId: processInstanceId,
						businessId: bussId,
						isHangUp: true
					});
				});
			});
			//解挂事件
		} else if (typeof($("#unHangUp")) != 'undefined' && $("#unHangUp").length > 0) {
			//流程被挂起禁用所有其他按钮
			$('#btnsWarp').find('.easyui-linkbutton ').linkbutton("disable");
			$('#unHangUp').linkbutton('enable');
			$("#unHangUp").bind("click", function() {
				if(btnDisabled($(this))){
					return
				}
				var hangUpUser = $("#hangUpUser").val();
				if (hangUpUser == currentUser) {
					showLoading();
					ajax.init().success(function(code, msg, datas) {
						hideLoading();
						window.location.reload();
					}).error(function(code, msg, datas) {
						hideLoading();
						if (code == 12) {
							alertMsg.alert("您不是挂起人，无权解挂该任务！");
						} else {
							alertMsg.show("解挂失败！");
						}
					}).post(BASEPATH + '/oa/act/activitiMain/hangUp.htm', {
						processInstanceId: processInstanceId,
						businessId: bussId,
						isHangUp: false
					});
				}else {
					hideLoading();
					alertMsg.alert("您不是挂起人，无权解挂该任务！");
				}
			});
		}
	}
});
